/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  Dimensions,
  TouchableOpacity,
  ListView,
  Alert,
  DeviceEventEmitter,
  ScrollView,
  NativeAppEventEmitter,
  AppState
} from 'react-native';

import ViewPager from 'react-native-viewpager';

var Slider = require('react-native-slider');
var Swiper = require('react-native-swiper')
var Header = require("./Component/Header");
var _navigator;

var valuet = [];

var DEFAULT_VALUE = 0;

import Slider1 from './components/Slider';
import styles1 from './styles/index.style';
import styles2 from './styles/Slider.style';
import { ENTRIES1, ENTRIES2 } from './static/entries';
import { sliderWidth, itemWidth } from './styles/SliderEntry.style';
import Carousel from 'react-native-snap-carousel';


import BleManager from 'react-native-ble-manager';

class SliderContainer extends Component{
  	constructor(props){
		super(props);	
		
	    this.state = {
	      	value: this.props.value,
	      	unit: this.props.unit
	    };
	    
	}

	render() {
	    var value = this.state.value+this.state.unit;
	
	    return (
		    <View>
		        <View style={styles.titleContainer}>
		          	<Text style={styles.caption} numberOfLines={1}>{this.props.caption}</Text>
		          	<View style={styles.border}>
		          		<Text style={styles.value} numberOfLines={1}>{value}</Text>
		          	</View>
		        </View>
		        {this._renderChildren()}
		    </View>
	    );
	}

	_renderChildren() {
	    return React.Children.map(this.props.children, (child) => {
	      	if (child.type === Slider
	          	|| child.type === ReactNative.Slider) {
	        var value = this.state.value;
	        return React.cloneElement(child, {
	          	value: value,
	          	onValueChange: (val) => this.setState({value: val}),
	        	});
	      	} else {
	        	return child;
	      	}
	    });
	}
}
 
class NodePage extends Component{
	constructor(props){
		super(props);	
	}
	
	render(){
		let value = this.props.mode;
		if(value === 0){
			return(
				<View style={{width:Dimensions.get('window').width-40}}>
					<View style={styles.list}>
						<SliderContainer caption="时间长度:" value={15} unit={"min"}>
					    <Slider
				            trackStyle={customStyles2.track}
				            thumbStyle={customStyles2.thumb}
				            minimumValue={0}
				            maximumValue={30}
				            step={1}
				            minimumTrackTintColor='#1073ff'
				            maximumTrackTintColor='#b7b7b7'
				            onSlidingComplete={(val)=>{this.props.timeCallback(val)}}
				        />
					    </SliderContainer>
	          		</View>
	          		<View style={styles.list}>
						<SliderContainer caption="震动强度:" value={100} unit={""}>
					    <Slider
				            trackStyle={customStyles2.track}
				            thumbStyle={customStyles2.thumb}
				            minimumValue={0}
				            maximumValue={100}
				            step={1}
				            minimumTrackTintColor='#1073ff'
				            maximumTrackTintColor='#b7b7b7'
				            onSlidingComplete={(val)=>{this.props.strongCallback(val)}}
				        />
					    </SliderContainer>
	          		</View>
          		</View>
			);
		}else if(value === 1){
			return(
				<View style={{width:Dimensions.get('window').width-40}}>
					<View style={styles.list}>
						<SliderContainer caption="时间强度:" value={15} unit={"min"}>
					    <Slider
				            trackStyle={customStyles2.track}
				            thumbStyle={customStyles2.thumb}
				            minimumValue={0}
				            maximumValue={30}
				            step={1}
				            minimumTrackTintColor='#1073ff'
				            maximumTrackTintColor='#b7b7b7'
				            onSlidingComplete={(val)=>{this.props.timeCallback(val)}}
				        />
					    </SliderContainer>
	          		</View>
	          		<View style={styles.list}>
						<SliderContainer caption="发热强度:" value={0} unit={""}>
					    <Slider
				            trackStyle={customStyles2.track}
				            thumbStyle={customStyles2.thumb}
				            minimumValue={0}
				            maximumValue={10}
				            step={1}
				            minimumTrackTintColor='#1073ff'
				            maximumTrackTintColor='#b7b7b7'
				            onSlidingComplete={(val)=>{this.props.hotCallback(val)}}
				        />
					    </SliderContainer>
	          		</View>
          		</View>
			);
		}
	}
}

class ControlPage extends Component {
	constructor(props) {  
		super(props);
		_navigator = this.props.navigator;
		var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

        this.state = {
        	dataSource1: ds,
            dataSource: ds.cloneWithRows(["时间长度:","按摩强度:"]),
			status:false,
			page:0,
			value:valuet,
			time:15,
			hot:0,
			strong:100,
			mode:this.props.mode,
			entries:["1","2","3"],
			imageList:[require("./image/ControlPage/status1.png"),
			require("./image/ControlPage/status2.png"),
			require("./image/ControlPage/status3.png"),
			require("./image/ControlPage/status4.png"),
			require("./image/ControlPage/status5.png")],
			modename:["丰韵提","畅美揉","润颜推","挺姿拍","丽质锤"],
			isconnect:true,
        };
        this._setMode();
        this._renderItem = this._renderItem.bind(this);
        this._onSnapToItem = this._onSnapToItem.bind(this);
  	}
	
	_setMode(){
		BleManager.isPeripheralConnected(this.props.bleid, [])
		  .then((isConnected) => {
		    if (isConnected) {
		      	if(this.state.mode == 0){
					var strong = this.state.strong;
					var mdata;
					if(this.state.status){
						mdata = [0x00,0x62,0x01,0xc0];
					}else{
						mdata = [0x00,0x62,strong,0x03,0x05,strong,this.state.page+1];	
					}
	
					var blewritecmd = {name:"Kbra",cmd:mdata};
		//			Alert.alert(JSON.stringify(blewritecmd));
					DeviceEventEmitter.emit('writeData',blewritecmd);
				}else if(this.state.mode == 1){
					var blewritecmd;
					if(this.state.status){
						var cmd = "AT+MODE[0,30]";
						blewritecmd = {name:"IDOLLY",cmd:cmd};
						console.log(cmd);
						
						DeviceEventEmitter.emit('writeData',blewritecmd);
						
						var cmd1 = "AT+PWM[1,0]";
						blewritecmd = {name:"IDOLLY",cmd:cmd1};
						DeviceEventEmitter.emit('writeData',blewritecmd);
					}else{
						var mode = this.state.page+1;
						var cmd = "AT+MODE["+mode.toString()+","+this.state.time.toString()+"]";
						blewritecmd = {name:"IDOLLY",cmd:cmd};
						DeviceEventEmitter.emit('writeData',blewritecmd);
						
						var cmd1 = "AT+PWM[1,"+(this.state.hot*10).toString()+"]";
						blewritecmd = {name:"IDOLLY",cmd:cmd1};
						DeviceEventEmitter.emit('writeData',blewritecmd);
		//				console.log(cmd);
					}
				}
		    } else {
		      console.log('Peripheral is NOT connected!');
		    }
		});
		
		
//					var strong = this.state.strong;
//			var mdata;
//			if(this.state.status){
//				mdata = [0x00,0x62,0x01,0xc0];
//			}else{
//				mdata = [0x00,0x62,strong,0x03,0x05,strong,this.state.page+1];	
//			}
//			var blewritecmd = {name:"Kbra",cmd:mdata};
//			console.log(blewritecmd);
	}
	
	_pressbtn(){
		//Alert.alert("123");
		
		this.setState({status:!this.state.status});
		setTimeout(()=>{this._setMode()},100);
		
//		var mode = this.state.page+1;
//		var cmd = "AT+MODE["+mode.toString()+","+this.state.time.toString()+"]";
//		
//  	Alert.alert(this.state.time.toString());
//		if(this.state.status){
//			DeviceEventEmitter.emit('writeData',-1);
//		}
//		else{
//			DeviceEventEmitter.emit('writeData',this.state.page);
//		}
	}
	                                      
	componentDidMount(){
		this._back = this._back.bind(this);
        DeviceEventEmitter
			.addListener('_back',this._back);
			
		this.BleManagerDisconnectPeripheral = this.BleManagerDisconnectPeripheral.bind(this);
      	NativeAppEventEmitter
           .addListener('BleManagerDisconnectPeripheral', this.BleManagerDisconnectPeripheral );
        
        this.BleManagerConnectPeripheral = this.BleManagerConnectPeripheral.bind(this);
      	NativeAppEventEmitter
           .addListener('BleManagerConnectPeripheral', this.BleManagerConnectPeripheral );
           
           
        this._handleAppStateChange = this._handleAppStateChange.bind(this);
        AppState.addEventListener('change', this._handleAppStateChange);
	}
	
	componentWillUnmount(){
		DeviceEventEmitter
			.removeListener('back',this._back);
		
		NativeAppEventEmitter
           .removeListener('BleManagerDisconnectPeripheral', this.BleManagerDisconnectPeripheral );
		NativeAppEventEmitter
           .removeListener('BleManagerConnectPeripheral', this.BleManagerConnectPeripheral );
           
		AppState.removeEventListener('change', this._handleAppStateChange);
		
		DeviceEventEmitter.emit('disconnect','1');
	}
	
	_handleAppStateChange(currentAppState) {
		console.trace(currentAppState);
		if(currentAppState === "active"){
			BleManager.isPeripheralConnected(this.props.bleid, [])
			  .then((isConnected) => {
			    if (isConnected) {
			      console.log('Peripheral is connected!');
			    } else {
			      this.BleManagerDisconnectPeripheral({"peripheral":this.props.bleid});
			    }
			});
		}
	}
	
	BleManagerConnectPeripheral(argus){
		this.setState({isconnect:true});
	}
	
	BleManagerDisconnectPeripheral(argus){
		this.setState({isconnect:false});
		Alert.alert( 
			'提醒',
            "连接已断开，是否重连",
            [
              {text: '确定', onPress: () =>{
              	BleManager.connect(argus.peripheral).then(() => {		
					Alert.alert("已经重新连接");
				}).catch((error) => {
					BleManagerDisconnectPeripheral(argus);
				});
              }},
              {text: '取消', onPress: () => _navigator.pop()},
            ]
		);
	}
	
	_back(){
		
		_navigator.pop();
	}
	
	_renderPage(data, pageID) {  
        return (  
            <Image  
                source={data}  
                style={styles.page}/>  
        );  
    }
    
    _onResponderRelease(e,state,context){
    	this.setState({page:state.index});
    	setTimeout(()=>{this._setMode()},100);
    }
    
    _timeCallback(val){
    	this.setState({time:val});
    	setTimeout(()=>{this._setMode()},100);
    }
    
    _hotCallback(val){
    	this.setState({hot:val});
    	setTimeout(()=>{this._setMode()},100);
    }
    
    _strongCallback(val){
    	this.setState({strong:val});
    	setTimeout(()=>{this._setMode()},100);
    }
    
	_renderItem(data, index){
		return(
			<View style={styles.tabmode}>
				<Image source={this.state.imageList[index]} style={styles.img}/>
			</View>
		);
	}
	
	_onSnapToItem(slideIndex, itemData){
		this.setState({page:slideIndex});
    	setTimeout(()=>{this._setMode()},100);
	}
	
//	                    <Slider1
//	                      	items={ENTRIES1}
//	                      	firstItem={2}
//	                      	inactiveSlideScale={0.94}
//	                      	inactiveSlideOpacity={0.6}
//	                    />
	render() {
		let img = (this.state.status==true)?'#00ff00':'#ff0000';
		let status = (this.state.status==true)?'START':'STOP';
		
	    return (
	      	<View style={styles.container}>
	      		<Header name={this.props.title} IconLeft="chevron-left" onPressLeft={()=>{_navigator.pop();}}/>
	      		<View style={{flex:1,alignItems: 'center',justifyContent: 'center'}}>
	      			<Text style={{fontSize:20}}>{this.state.modename[this.state.page]}</Text>
	      			<Carousel 
	      				items={ENTRIES1}
			            renderItem={this._renderItem}
			            sliderWidth={sliderWidth}
			            itemWidth={itemWidth}
			            slideStyle={styles2.slide}
			            containerCustomStyle={styles2.slider}
			            contentContainerCustomStyle={styles2.sliderContainer}
			            showsHorizontalScrollIndicator={false}
			            snapOnAndroid={true}
			            removeClippedSubviews={false}
			            onSnapToItem={this._onSnapToItem}
			        />
	      		</View>
	      		<View style={{marginBottom:0,alignItems: 'center'}}>
	      			<TouchableOpacity onPress={this._pressbtn.bind(this)}>
	      				<View style={[{borderColor:img},styles.clybutton]}>
	      					<Text style={{fontWeight:'bold'}}>{status}</Text>
	      				</View>
	      			</TouchableOpacity>
	      		</View>
	      		<View style={{alignItems: 'center'}}>
	      			<NodePage 
	      				mode={this.props.mode}
						timeCallback={(val)=>this._timeCallback(val)}
	      				hotCallback={(val)=>this._hotCallback(val)}
	      				strongCallback={(val)=>this._strongCallback(val)}
	      			/>
	      		</View>
	      	</View>
	    );
	}
}
//mode={this.props.mode}
const styles = StyleSheet.create({
	container: {
	    flex: 1,
	    alignItems: 'center',
	    backgroundColor: '#FAF4FF',
	},
	image1:{
		width:200,
		height:200,
		resizeMode: 'contain',
	},
	clybutton:{
		borderWidth:5,
		height:80,
		width:80,
		borderRadius:40,
		justifyContent: 'center',
	    alignItems: 'center',
	},
	slider:{
		width:Dimensions.get('window').width-20,
		
	},
	wrapper:{
		height:200
	},
	title:{
		flexDirection:'row',
		width:Dimensions.get('window').width-40,
		marginLeft:10,
		marginRight:10,
	},
	list:{
		height:90,
		justifyContent: 'center',
	},
	titleContainer:{
		flexDirection:'row',
		alignItems: 'center',
	},
	caption:{
		fontSize:15,
	},
	value:{
		padding:3,
		fontSize:12,
	},
	border:{
		marginLeft:10,
		borderWidth:0,
		borderRadius:15,
		width:60,
		alignItems: 'center',
		backgroundColor:'#FFB6C1'
	},
	img:{ 
	    width:215,
	    height:218, 
	}, 
	tabmode:{
		width:Dimensions.get('window').width-130,
		height:Dimensions.get('window').width-130,
		alignItems: 'center',
		justifyContent: 'center', 
	} 
});

var customStyles2 = StyleSheet.create({
  track: {
    height: 4,
    borderRadius: 2,
  },
  thumb: {
    width: 30,
    height: 30,
    borderRadius: 30 / 2,
    backgroundColor: 'white',
    borderColor: '#888888',
    borderWidth: 2,
  }
});

var customStyles3 = StyleSheet.create({
  track: {
    height: 10,
    borderRadius: 5,
    backgroundColor: '#ffffff',
  },
  thumb: {
    width: 10,
    height: 30,
    borderRadius: 5,
    backgroundColor: '#eb6e1b',
  }
});

module.exports = ControlPage;
